package cn.rongdao.jrkabao.ui.webview;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebView;

import com.mifengkong.frtools.http.request.callback.BaseImpl;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.http.util.CookieConstant;
import com.mifengkong.frtools.jsbridge.BridgeWebView;
import com.mifengkong.frtools.jsbridge.BridgeWebViewClient;
import com.mifengkong.frtools.jsbridge.CallBackFunction;
import com.mifengkong.frtools.system.handler.FRMainLooperHandler;
import com.mifengkong.frtools.util.FRDeviceUtil;
import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frwidget.titlebar.WebViewTitleBarUIComponent;
import com.mifengkong.frwidget.webview.MyWebChromeClient;
import com.mifengkong.im.huanxin.EMChatLoginUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;

import cn.mifengkong.appcommon.util.ChannelUtil;
import cn.mifengkong.appcommon.webview.DataJavascriptInterface;
import cn.mifengkong.appcommon.webview.jshandler.GetDataJSHandler;
import cn.mifengkong.appcommon.webview.listener.JsBridgeCallBackListener;
import cn.mifengkong.appcommon.webview.listener.JsCallBackListener;
import cn.mifengkong.appcommon.webview.uicomponent.WebViewUIComponent;
import cn.mifengkong.appcommon.webview.uicomponent.WebviewDataConfig;
import cn.rongdao.jrkabao.BuildConfig;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.constant.AppConstant;
import cn.rongdao.jrkabao.constant.InfoConstant;
import cn.rongdao.jrkabao.dao.CityDao;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.cashadvance.CollectWebViewMsgModel;
import cn.rongdao.jrkabao.ui.cashadvance.event.ProtocolSuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.manager.LivenessManager;
import cn.rongdao.jrkabao.ui.login.LoginActivity;
import cn.rongdao.jrkabao.ui.main.MainActivity;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.LoginUtil;
import cn.rongdao.jrkabao.util.NetWorkUtil;


/**
 * Created by jiangyongxing on 2017/11/17.
 * 描述：webview的帮助类  帮助webview做一些比较琐碎的事情
 */

public class WebViewHelper implements JsCallBackListener, JsBridgeCallBackListener {

    private BaseImpl baseImpl;
    private WebViewUIComponent webViewUIComponent;
    private WebViewTitleBarUIComponent titleBarUIComponent;
    private DataJavascriptInterface mDataJavascriptInterface;

    private String mTitle = "正在加载中...";
    private boolean isErrorPage = false;
    private OnWebViewCallBack onWebViewCallBack;
    private WebviewDataConfig mWebviewDataConfig;

    private String url;
    private LivenessManager mLivenessManager;

    @SuppressLint("AddJavascriptInterface")
    public WebViewHelper(BaseImpl baseImpl, WebViewUIComponent webViewUIComponent, WebViewTitleBarUIComponent titleBarUIComponent) {
        this.baseImpl = baseImpl;
        this.webViewUIComponent = webViewUIComponent;
        webViewUIComponent.setProgressBarDrawable(R.drawable.progressbar_bg);
        webViewUIComponent.setTvRefreshBackground(R.drawable.no_net_work_50radius, ContextCompat.getColor(baseImpl.getActivity(), R.color.colorPrimary));
        mDataJavascriptInterface = new DataJavascriptInterface(baseImpl.getActivity(), this);
        webViewUIComponent.getWebViewUIComponent().getWebView().addJavascriptInterface(mDataJavascriptInterface, "onCallByH5");
        this.titleBarUIComponent = titleBarUIComponent;
        mLivenessManager = new LivenessManager(baseImpl);
        mLivenessManager.initLivenessDialog(titleBarUIComponent);

        initParams();
        initListener();
    }

    private void initListener() {
        webViewUIComponent.setWebViewGetTitle(new MyWebChromeClient.OnGetTitleClick() {
            @Override
            public void getTitle(View view, String title) {
                if (baseImpl.getActivity() instanceof MainActivity){
                    isCloseVisible();
                }
                mTitle = title;
                if (CommonUtil.isContainChinese(title)) {
                    setTitle(title);
                } else {
                    setTitle("");
                }
            }
        });
        webViewUIComponent.getWebViewUIComponent().getWebView().setWebViewClient(new BridgeWebViewClient((BridgeWebView) webViewUIComponent.getWebViewUIComponent().getWebView()) {
            /**
             * 捕获Url
             * 多页面在统一WebView中打开`
             * @param view
             * @param urlString
             * @return
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String urlString) {
                super.shouldOverrideUrlLoading(view, urlString);
                //是否拦截到打电话的Intent
                if (webViewUIComponent.startTelActivity(baseImpl.getActivity(), urlString)) {
                    return true;
                }
                if (null != onWebViewCallBack && onWebViewCallBack.shouldOverrideUrlLoading(view, urlString)) {
                    return true;
                }
                if (webViewShouldOverrideUrlLoading(view, urlString)) return true;
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webViewUIComponent.setDataToLocalStorage();
                if (mTitle.equals("正在加载中...")) {
                    setTitle("");
                }
                if (null != onWebViewCallBack) {
                    onWebViewCallBack.onPageFinished(view, url);
                }
                isErrorPage = !NetWorkUtil.IsNetWorkEnable(baseImpl.getActivity());
                if (!isErrorPage) {
                    FRMainLooperHandler.getInstance().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (null != webViewUIComponent) {
                                webViewUIComponent.setRefreshLayoutVisible(false);
                            }
                        }
                    }, 200);
                    webViewUIComponent.getWebViewUIComponent().onPageFinished(url);
                } else {
                    webViewUIComponent.setRefreshLayoutVisible(true);
                }
            }
        });
    }

    private boolean webViewShouldOverrideUrlLoading(WebView view, String urlString) {
        if (urlString.startsWith(InfoConstant.YY_OVERRIDE_SCHEMA)) {
            //如果捕捉到的是jsBridge的两个头地址，就不执行
            return true;
        }
        boolean networkUrl = URLUtil.isNetworkUrl(urlString);
        boolean shouldLoadingUrlByAndroidVersion = webViewUIComponent.shouldLoadingUrlByAndroidVersion();
        if (networkUrl && shouldLoadingUrlByAndroidVersion) {
            view.loadUrl(urlString);
            return true;
        }
        return networkUrl == shouldLoadingUrlByAndroidVersion;
    }

    private void delayClearHistory(int delayTime) {
        FRMainLooperHandler.getInstance().postDelayed(new Runnable() {
            @Override
            public void run() {
                webViewUIComponent.getWebViewUIComponent().getWebView().clearHistory();
            }
        }, delayTime);
    }

    private void isCloseVisible() {
        try {
            if (webViewUIComponent.getWebViewUIComponent().getWebView().getUrl().equalsIgnoreCase(url)) {
                titleBarUIComponent.setLeftIsVisible(false);
            } else {
                titleBarUIComponent.setLeftIsVisible(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void logOut() {
        LoginUtil.logout(baseImpl.getActivity());
        webViewUIComponent.userLogout();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mLivenessManager.onActivityResult(requestCode, resultCode, data);
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        mLivenessManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void showCustomServiceDialog() {
        baseImpl.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (baseImpl.getActivity() instanceof WebViewActivity) {
                    ((WebViewActivity) baseImpl.getActivity()).showLoanConsultDialog();
                } else if (baseImpl.getActivity() instanceof MainActivity) {
                    ((MainActivity) baseImpl.getActivity()).showLoanConsultDialog();
                }
            }
        });
    }

    @Override
    public void startLoginActivity() {
        LoginActivity.start(baseImpl.getActivity());
    }

    @Override
    public String getPackageName() {
        return BuildConfig.APPLICATION_ID;
    }

    @Override
    public void getCashFailureMessage(String msg, String url) {
        CollectWebViewMsgModel.getInstance().execute(msg, url, new FRBaseObserver<String>(baseImpl) {
            @Override
            protected void onBaseNext(String data) {

            }
        });
    }

    @Override
    public void startMainActivity() {
        MainActivity.Companion.start(baseImpl.getActivity());
        if (baseImpl.getActivity() instanceof WebViewActivity) {
            baseImpl.getActivity().finish();
        }
    }

    @Override
    public void startMoxieActivity(String moxieParmas) {

    }

    @Override
    public void closeWebView() {
        if (baseImpl.getActivity() instanceof WebViewActivity) {
            EventBus.getDefault().post(new ProtocolSuccessEvent());
            baseImpl.getActivity().finish();
        }
    }

    @Override
    public void showNextFragment(Activity context) {

    }

    public void loadUrlAndSetLocalStorage(String url) {
        this.url = url;
        CommonUtil.setCookie(baseImpl.getActivity(), url, FRSharedPreferences.getStringSet(CookieConstant.SP_NAME_COOKIES, CookieConstant.PREF_COOKIES, new HashSet<String>()));
        webViewUIComponent.initJsHandler(this, titleBarUIComponent);
        webViewUIComponent.loadUrlAndData(url);
        webViewUIComponent.setDataToLocalStorage();
        webViewUIComponent.initUserAgent(BuildConfig.VERSION_NAME);
    }

    public void initParams() {
        mWebviewDataConfig = new WebviewDataConfig.Builder()
                .setUserId(UserDao.getInstance().getUserId())
                .setToken(UserDao.getInstance().getToken())
                .setPhone(UserDao.getInstance().getPhone())
                .setAppVersion(BuildConfig.VERSION_NAME)
                .setPlatVersion(BuildConfig.VERSION_NAME)
                .setPlatType(AppConstant.ANDROID)
                .setAppUnionName(AppConstant.APPUNIONNAME)
                .setCityId(CityDao.getInstance().getCityId())
                .setPackageName(BuildConfig.APPLICATION_ID)
                .setAppName(baseImpl.getActivity().getString(R.string.app_name))
                .setDevBrand(FRDeviceUtil.getPhoneBrand())
                .setUUID(FRDeviceUtil.getDeviceId(baseImpl.getActivity()))
                .setCountryCode(FRDeviceUtil.getCountry())
                .setModel(FRDeviceUtil.getPhoneModels())
                .setNetInfo(NetWorkUtil.getCurrentNetworkType())
                .setAndroidVersion(String.valueOf(Build.VERSION.SDK_INT))
                .setSourceId(ChannelUtil.getChannelName(baseImpl.getActivity()))
                .setScreentSzie(TextUtils.concat(String.valueOf(FRDisplayMetrics.getScreenWidth(baseImpl.getActivity())), "*"
                        , String.valueOf(FRDisplayMetrics.getScreenHeight(baseImpl.getActivity()))).toString())
                .setMobleOperators(com.mifengkong.frtools.util.NetWorkUtil.getProvider())
                .setLanguageCode(FRDeviceUtil.getLanguage())
                .setEquipmentCapacity(FRDeviceUtil.getSDTotalSize(baseImpl.getActivity()))
                .create();

        webViewUIComponent.initConfig(mWebviewDataConfig);
        webViewUIComponent.registerHandler(baseImpl.getActivity().getString(R.string.js_handler_function_name_getdate), new GetDataJSHandler(mWebviewDataConfig));
    }

    public void setTitle(String title) {
        if (!FRString.isEmpty(title)) {
            titleBarUIComponent.initTitle(title);
        } else {
            titleBarUIComponent.initTitle("");
        }
    }

    public void initTitleBar(@DrawableRes int drawableResLeft, @DrawableRes int drawableResRight) {
        setTitle("正在加载中...");
        titleBarUIComponent.setBackgroundColor(ContextCompat.getColor(baseImpl.getActivity(), R.color.colorPrimary));
        if (drawableResLeft != 0) {
            titleBarUIComponent.initLeft(drawableResLeft, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (baseImpl.getActivity() instanceof MainActivity) {
                        webViewUIComponent.loadUrlAndData(url);
                        delayClearHistory(500);
                    } else if (baseImpl.getActivity() instanceof WebViewActivity) {
                        closeActivity();
                    }
                }
            });
        }

        if (drawableResRight != 0) {
            titleBarUIComponent.initRight(drawableResRight, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refreshLoad();
                }
            });
        }

        webViewUIComponent.setRefreshOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLoad();
            }
        });
    }

    public void setOnWebViewCallBack(OnWebViewCallBack onWebViewCallBack) {
        this.onWebViewCallBack = onWebViewCallBack;
    }

    public void closeActivity() {
        baseImpl.getActivity().finish();
    }

    @Override
    public void postData(String responeData) {

    }

    @Override
    public void startCustomerService() {
        EMChatLoginUtils.getInstance().chatWithService(baseImpl.getActivity(), R.color.colorPrimary);
    }

    @Override
    public void startCardManagerLoginDialog() {

    }

    @Override
    public boolean userDialogLoginType(String[] nameAndParamters) {
        return false;
    }

    @Override
    public void aliPay(String orderInfo) {

    }

    @Override
    public void dataImport(String code, String productId) {

    }

    @Override
    public void getCreditCardJSByCode(String code) {

    }

    @Override
    public void toStartLivingDetection(CallBackFunction function) {
        mLivenessManager.setStrJs(function);
        mLivenessManager.startLivenessActiviity(titleBarUIComponent);
    }

    @Override
    public void luanchMiniProgram(String miniProgramId, String path, int type) {

    }

    @Override
    public void shareUmeng(String responseData) {

    }

    public void refreshLoad() {
        if (null != webViewUIComponent) {
            webViewUIComponent.refresh();
        }
    }

    public boolean onKeyDown(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webViewUIComponent.isWebViewCanGoBack()) {
                webViewUIComponent.goBack();
                return true;
            }
        }
        return false;
    }


    public void onStop() {
        mDataJavascriptInterface.setProgressDialogDiamiss();
    }

    public void onDestroy() {
        try {
            webViewUIComponent.onDestroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnWebViewCallBack {
        boolean shouldOverrideUrlLoading(WebView view, String urlString);

        void onPageFinished(WebView view, String url);
    }
}